{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "TryCatch实际上是一种隐式的机制来对待错误的程序，它的好处在于错误发生了可以继续运行下去，坏处是可以不负责任的让错误不断地执行下去。并且，这种错误虽然也会得到CallStack的形式，但是当问题的层级越来越深，上下文变得复杂，实际上就是无法处理的情况。\n",
    "\n",
    "一个更加清晰地改进意见是学习Rust的方式是确定Success或者False的返回Result。这意味着，"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Result:\n",
    "    def __init__(self, value=None, error=None):\n",
    "        self.value = value\n",
    "        self.error = error\n",
    "\n",
    "    def is_ok(self):\n",
    "        return self.error is None\n",
    "\n",
    "    def is_err(self):\n",
    "        return self.error is not None\n",
    "\n",
    "    def unwrap(self):\n",
    "        if self.is_ok():\n",
    "            return self.value\n",
    "        else:\n",
    "            raise Exception(self.error)\n",
    "\n",
    "    def unwrap_err(self):\n",
    "        if self.is_err():\n",
    "            return self.error\n",
    "        else:\n",
    "            raise Exception(\"Called `Result::unwrap_err` on an `Ok` value\")\n",
    "\n",
    "    def map(self, func):\n",
    "        if self.is_ok():\n",
    "            return Result(func(self.value))\n",
    "        else:\n",
    "            return self\n",
    "\n",
    "    def map_err(self, func):\n",
    "        if self.is_err():\n",
    "            return Result(error=func(self.error))\n",
    "        else:\n",
    "            return self\n",
    "\n",
    "    def and_then(self, func):\n",
    "        if self.is_ok():\n",
    "            return func(self.value)\n",
    "        else:\n",
    "            return self\n",
    "\n",
    "    @staticmethod\n",
    "    def ok(value):\n",
    "        return Result(value=value)\n",
    "\n",
    "    @staticmethod\n",
    "    def err(error):\n",
    "        return Result(error=error)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用示例\n",
    "def divide(a, b):\n",
    "    try:\n",
    "        result = a / b\n",
    "        return Result.ok(result)\n",
    "    except ZeroDivisionError as e:\n",
    "        return Result.err(str(e))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 成功的情况\n",
    "print(divide(10, 2).unwrap())  # 输出 5.0\n",
    "\n",
    "# 失败的情况\n",
    "try:\n",
    "    print(divide(10, 0).unwrap())\n",
    "except Exception as e:\n",
    "    print(e)  # 输出 \"division by zero\""
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
